<template>
  <div class="flex flex-row w-full gap-[20px]">
    <div class="w-2/12">
      <!-- import DeviceSelectTree from "@/components/deviceSelectTree.vue"; -->
      <!-- @on-load 当树结构数据渲染完成后调用     -->
      <!-- @on-change 当值发生改变时候调用  -->
      <device-select-tree
        @on-load="
          (defaultSelectKeyObj, selectedParentNodes) => {
            console.log('数据加载了一次')
            changeDeviceHandle('', selectedParentNodes, defaultSelectKeyObj)
          }
        "
        @on-change="changeDeviceHandle"
      >
        <!-- 书选项的卡片标题       -->
        <template #card-title> <IconList />&nbsp;分系统选项 </template>
        <!--一共两个slot 分别为title 和 extra       -->
        <!-- title 是树节点的标题
        注入了三个参数
        nodeData：当前节点数据
        switchNode：调用切换节点的函数，会影响value （必须调用此函数的实现，否则无法选择节点）
        value：当前选中的key
        selectedParentNodes：当前选中项的所有父节点
        -->
        <template #title="{ nodeData, switchNode, value }">
          <template v-if="nodeData.deviceId">
            <a-button
              @click="switchNode(nodeData.code, nodeData)"
              size="mini"
              :type="nodeData.code === value ? 'primary' : 'text'"
              >{{ nodeData.name }}
            </a-button>
          </template>
          <template v-else>
            <span class="text-gray-700">{{ nodeData.name }}</span>
          </template>
        </template>
        <!-- extra 是树节点的扩展选项，一般是每个节点尾部的按钮区域
        注入了三个参数
        nodeData：当前节点数据
        switchNode：调用切换节点的函数，会影响value
        value：当前选中的key
        selectedParentNodes：当前选中项的所有父节点
        -->
        <template #extra="{ nodeData, value, selectedParentNodes }">
          <template v-if="nodeData.deviceId">
            <a-tooltip content="设置告警规则">
              <a-button type="text" @click="openWarningSetting(nodeData, selectedParentNodes)">
                <IconSettings style="position: absolute; right: 8px; font-size: 12px; top: 10px; color: #3370ff" />
              </a-button>
            </a-tooltip>
          </template>
        </template>
      </device-select-tree>
      <warning-setting
        v-if="warningData.visible"
        :visible="warningData.visible"
        @close="closeWarningSetting"
        :device-data="warningData.data"
        :parent-nodes="warningData.selectedParentNodes"
      />
    </div>
    <div class="flex-auto h-[calc(100vh-150px)] overflow-y-auto">
      <a-card title="趋势图">
        <template #extra>
          <div>
            <a-space>
              <a-select
                placeholder="请选择告警等级"
                v-model="data.search.level"
                style="width: 100px"
                @change="getEchartsData"
              >
                <a-option :value="1">1级</a-option>
                <a-option :value="2">2级</a-option>
                <a-option :value="3">3级</a-option>
                <a-option :value="4">4级</a-option>
                <a-option :value="5">5级</a-option>
                <a-option :value="6">6级</a-option>
                <a-option :value="7">7级</a-option>
              </a-select>
              <a-button-group>
                <template v-for="item in data.planDateOptions" :key="item.value">
                  <a-button
                    class="!rounded-none"
                    :type="equalDateRange(data.search.timeRange, item.dateRange) ? 'primary' : 'text'"
                    @click="handleClick(item)"
                    >{{ item.label }}
                  </a-button>
                </template>
              </a-button-group>
              <a-range-picker
                showTime
                allow-clear
                v-model="data.search.timeRange"
                class="!w-[360px] inline-block"
                @change="searchHandle"
              ></a-range-picker>
            </a-space>
          </div>
        </template>
        <div id="Echarts" style="width: 100%; height: 400px"></div>
      </a-card>
      <a-card class="mt-[20px]">
        <a-tabs v-model:active-key="activeKey">
          <a-tab-pane key="threshold" title="门限告警">
            <Threshold v-if="activeKey === 'threshold'" />
          </a-tab-pane>
          <a-tab-pane key="constant" title="常值监测">
            <Constant v-if="activeKey === 'constant'" />
          </a-tab-pane>
          <a-tab-pane key="analyse" title="关联分析">
            <Analyse v-if="activeKey === 'analyse'" />
          </a-tab-pane>
          <a-tab-pane key="dataCompute" title="时序数据计算">
            <DataCompute v-if="activeKey === 'dataCompute'" />
          </a-tab-pane>
          <a-tab-pane key="complexModel" title="复杂模型">
            <ComplexModel v-if="activeKey === 'complexModel'" />
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import { apiHome } from '@/api/strategy.js'

import Threshold from './threshold.vue'
import Constant from './constant.vue'
import Analyse from './analyse.vue'
import ComplexModel from './complexModel.vue'
import DataCompute from './dataCompute.vue'
import DeviceSelectTree from '@/components/deviceSelectTree.vue'
import WarningSetting from '@/views/strategyRecommendation/components/warningSetting.vue'

const handleClick = (item) => {
  data.search.timeRange = item.dateRange
  data.search.type = item.value
  getEchartsData()
}

const warningData = reactive({
  visible: false,
  data: null,
  selectedParentNodes: []
})
const openWarningSetting = (data, selectedParentNodes) => {
  warningData.data = data
  warningData.selectedParentNodes = selectedParentNodes
  warningData.visible = true
}
const closeWarningSetting = () => {
  warningData.visible = false
  warningData.data = null
  warningData.selectedParentNodes = []
}
const changeDeviceHandle = (deviceId, node, parentNodes) => {
  console.log(parentNodes)
  data.deviceObj = node
  // data.satelliteObj = parentNodes.find(item => Object.prototype.hasOwnProperty.call(item, "twoline"))
  data.satelliteObj = findObjWithTwoline(parentNodes)
  // console.log(data.satelliteObj, 'data.satelliteObj')
  data.search.deviceId = deviceId
  getEchartsData(deviceId, node)
}

const findObjWithTwoline = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    const obj = arr[i]
    if (Object.prototype.hasOwnProperty.call(obj, 'twoline')) {
      return obj
    }
    if (obj.children) {
      const result = findObjWithTwoline(obj.children)
      if (result) {
        return result
      }
    }
  }
  return null
}

const data = reactive({
  planDateOptions: [
    {
      label: '今日',
      value: 1,
      dateRange: [dayjs().startOf('day').toDate(), dayjs().endOf('day').toDate()]
    },
    {
      label: '近7天',
      value: 2,
      dateRange: [dayjs().startOf('day').subtract(1, 'week').toDate(), dayjs().endOf('day').toDate()]
    },
    {
      label: '近一月',
      value: 3,
      dateRange: [dayjs().startOf('day').subtract(1, 'month').toDate(), dayjs().endOf('day').toDate()]
    },
    {
      label: '近一年',
      value: 4,
      dateRange: [dayjs().startOf('day').subtract(1, 'year').toDate(), dayjs().endOf('day').toDate()]
    }
  ],
  search: {
    level: 5, // 告警等级
    timeRange: [dayjs().startOf('day').toDate(), dayjs().endOf('day').toDate()],
    type: 1 // 1:今日 2:近7天 3:近一月 4:近一年
  },
  paginationData: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  satelliteObj: {},
  deviceObj: {}
})

const activeKey = ref('threshold')

const equalDateRange = (targetRange, range) => {
  if (range.length === 0) {
    if (targetRange === undefined) {
      return true
    }
    if (targetRange.length === 0) {
      return true
    }
    if (Array.isArray(targetRange) && targetRange[0] === null) {
      return true
    }
  }
  return Array.isArray(targetRange) && dayjs(targetRange[0]).isSame(range[0]) && dayjs(targetRange[1]).isSame(range[1])
}

const searchHandle = () => {
  data.search.type = 0
  getEchartsData()
}

const initChart = (value) => {
  if (echarts.getInstanceByDom(document.getElementById('Echarts'))) {
    echarts.dispose(document.getElementById('Echarts'))
  }
  const myChart = echarts.init(document.getElementById('Echarts'))
  const options = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {},
    xAxis: {
      type: 'category',
      data: value[Object.keys(value).filter((key) => value[key].length > 0)[0]]?.map((item) =>
        data.search.type === 1 ? item.dataTime + '点' : item.dataTime
      )
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '门限告警',
        data: value.thresholdRecordList?.map((item) => item.num),
        type: 'bar',
        stack: 'a'
      },
      {
        name: '常值监测',
        data: value.constantMonitorRecordList?.map((item) => item.num),
        type: 'bar',
        stack: 'a'
      },
      {
        name: '关联分析',
        data: value.analyseResultRecordList?.map((item) => item.num),
        type: 'bar',
        stack: 'a'
      },
      {
        name: '时序数据计算',
        data: value.timeSeriesRecordRecordList?.map((item) => item.num),
        type: 'bar',
        stack: 'a'
      },
      {
        name: '复杂模型',
        data: value.modelInferenceRecordRecordList?.map((item) => item.num),
        type: 'bar',
        stack: 'a'
      }
    ]
  }
  myChart.setOption(options, true)
}

const getEchartsData = (deviceId, node) => {
  console.log('当选项发生变化后，回调', deviceId, node)
  // const echartsData = Array.from({ length: 3 }, () =>
  //   Array.from({ length: 7 }, () => Math.floor(Math.random() * 500))
  // );
  const params = {
    level: data.search.level,
    satId: data.satelliteObj.satId,
    deviceId: data.deviceObj.deviceId,
    type: data.search.type,
    startTime: dayjs(data.search.timeRange[0]).format('YYYY-MM-DD HH:mm:ss'),
    endTime: dayjs(data.search.timeRange[1]).format('YYYY-MM-DD HH:mm:ss')
  }
  apiHome.getAlarmChart(params).then((res) => {
    if (res.code === 200) {
      initChart(res.data)
    }
  })
}

onMounted(() => {
  // getEchartsData();
})
</script>

<style></style>
